package consoleView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import model.Puzzle;

/*
 * Created on January 23, 2006
 */

/**
 * @author Beth Katz
 * The TextView class prints puzzles and answers in the console 
 */

public class ConsoleUI {

	Puzzle thePuzzle;

	private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );

	/**
	 * Constructor for TextView class does nothing
	 */
	public ConsoleUI( )	{
	}

	/**
	 * sets the puzzle object 
	 */
	public void setPuzzle(Puzzle p) {
		thePuzzle = p;
	}

	/**
	 * prints the puzzle
	 */
	public void printPuzzle( ) {
		int theRows = thePuzzle.numberOfRows( );
		int theCols = thePuzzle.numberOfColumns( );

		for (int i = 1; i <= theRows; i++) {
			for (int j = 1; j <= theCols; j++) {
				System.out.print(thePuzzle.charAt(i,j) + " ");
			}
			System.out.println( );
		}		
	}

	/**
	 * prints a message to the console
	 */
	public void printMessage(String theMessage) {
		System.out.println(theMessage);
	}

	/**
	 * reads a word from the user and returns it
	 */
	public String getWord( ) {
		String theWord;

		try {
			System.out.println("Enter word: ");
			theWord = in.readLine( );
			if (theWord == null || (theWord.length() == 1) && (theWord.charAt(0) == '!')) { 
				// workaround for Eclipse EOF
				throw new IOException( );
			}
		} catch (IOException e) {
			return "!";
		}
		return theWord;
	}

	   /**
     * reads words from the user and find them in the puzzle
     */
    public void findWords ( ) {
        String theWord, theAnswer;
        int wordCount = 0;
 
        while (true)
        {
            try
            {
            	theWord = getWord( );
            	if (theWord.length() > 0) {
            		if ((theWord.length( ) == 1) && (theWord.charAt(0)== '!')) { // workaround for Eclipse EOF
            			throw new IOException( );
            		}
            		wordCount++;
            		theAnswer = thePuzzle.locationInPuzzle(theWord);
            		if (theAnswer.length( ) > 0) {
            			printMessage(theAnswer);
            		} else {
            			printMessage( theWord + " was not found");
            		}
            	}
            }
            catch ( IOException e ) {
            	printMessage( wordCount + " words considered.");
            	return;
            }
        }
    }

	/**
	 * obtains a file name from the user and returns it
	 */
	public String obtainFileName(String message) {
		String theName;

		try {
			System.out.println(message);
			theName = in.readLine( );
			if (theName.length() == 0) { 
				throw new IOException( );
			}
		} catch (IOException e) {
			return "";
		}
		return theName;
	}


}
